package cn.lianxi.kaoshi._09_;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

/**
 * Description: 这是自定义的Hadoop序列化类，它可以用Hadoop序列化反序列化这个类
 */
public class StudentWritable implements WritableComparable<StudentWritable> {

	private Text name;
	private IntWritable age;
	private Text title;

	public StudentWritable() {
		set("someperson", 0, "sometitle");
	}

	public StudentWritable(String name, int age, String title) {
		set(name, age, title);
	}

	public void set(String name, int age, String title) {
		this.name = new Text(name);

		age = (age > 0) ? age : 1;
		this.age = new IntWritable(age);

		this.title = new Text(title);
	}

	/**
	 * 这个方法用于定义序列化过程，它把这个对象的所有字段依次序列化
	 */
	@Override
	public void write(DataOutput out) throws IOException {
		// TODO Auto-generated method stub

		name.write(out);
		age.write(out);
		title.write(out);

	}

	/**
	 * 这个方法用于定义反序列化过程，它吧序列化后的DataInput的内容还原为Hadoop对象
	 */
	@Override
	public void readFields(DataInput in) throws IOException {
		// TODO Auto-generated method stub

		name.readFields(in);
		age.readFields(in);
		title.readFields(in);

	}

	/**
	 * 这是用于2个序列化对象之间的比较
	 */
	@Override
	public int compareTo(StudentWritable pO) {
		// TODO Auto-generated method stub
		int cmp1 = name.compareTo(pO.name);
		if (cmp1 != 0) {
			return cmp1;
		}

		int cmp2 = age.compareTo(pO.age);
		if (cmp2 != 0) {
			return cmp2;
		}

		int cmp3 = title.compareTo(pO.title);
		return cmp3;
	}

	/**
	 * 定义hashcode是个好习惯，我们还是使用最常用的字段分别乘以不同的素数然后相加的方法
	 */
	@Override
	public int hashCode() {
		return name.hashCode() * 71 + age.hashCode() * 73 + title.hashCode()
				* 127;
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof StudentWritable) {

			StudentWritable pw = (StudentWritable) o;
			boolean equals = name.equals(pw.name) && age.equals(pw.age)
					&& title.equals(pw.title);
			return equals;
		}
		return false;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		sb.append("姓名： " + name + ",");
		sb.append("年龄: " + age + ",");
		sb.append("头衔： " + title);
		sb.append("]");
		return sb.toString();
	}

}